package com.jingli.pile.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class MessageEncryption {
    private static final String AES_ALGORITHM = "AES/CBC/PKCS5Padding";
    private static final String CHARSET = "UTF-8";

    // 加密方法
    public static String encrypt(String data, String key, String iv) throws Exception {
        Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));

        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));

        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    // 解密方法
    public static String decrypt(String encryptedData, String key, String iv) throws Exception {
        Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));

        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));

        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    public static void main(String[] args) {
        try {
            String data = "O6CZGGG5c7ZY8W9m2mbUXCKW1oj4nlkj9AjhqJaIqGTtjftQujneF8L6aYkEPiEEHC503YVZ2ijlQhQSk21baA==";
            String key = "fwpammxo0lw0lzyu"; // 16字节的密钥
            String iv = "unoh6lpsulze2y30"; // 16字节的初始向量
            String sigSecret = "8qkuf011kzwjsn9t";
            String platformID = "MA8N2HC57";
            String timestamp = "20231124162727";
            String seq = "0001";

//            // 加密
//            String encryptedData = encrypt(data, key, iv);
//            System.out.println("加密后的数据：" + encryptedData);

            // 解密
            String decryptedData = decrypt(data, key, iv);
            System.out.println("解密后的数据：" + decryptedData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
